#!/bin/python
import json
import os

try:
    import ConfigParser
except ImportError:
    import configparser as ConfigParser
import argparse


class JsonParser:
    def __init__(self, cf):
        self.json_file = cf

    def parse(self):
        group_base = dict()
        net_base = dict()
        fr = open(self.json_file, 'r')
        info = json.load(fr)
        for key, value in info.items():
            if (key != 'simulation'):
                continue
            sim_dict = value
        for key, value in sim_dict.items():
            if (key == 'Components'):
                comp_base = value
            elif (key == 'chiplets'):
                for k, v in value.items():
                    # print(k,v)
                    if (k == 'GroupNum' or k == 'Interconnect'):
                        net_base.update(v)
                group_base.update(self.group_basecfg(value, comp_base))
        # print(net_base)
        # print(group_base)
        return group_base, net_base

    def group_basecfg(self, group, comp):
        for key, value in group.items():
            if (key == 'GroupNum' or key == 'Interconnect'):
                continue
            if ('CPU_type' not in value.keys()):
                print("*****Error: group %s has not specified CPU type" % key)
                sys.exit()
            cpu_type = value['CPU_type']
            value['CPU'] = comp[cpu_type]

            if ('GPU_type' not in value.keys()):
                print("*****Error: group %s has not specified GPU type" % key)
                sys.exit()
            gpu_type = value['GPU_type']
            value['GPU'] = comp[gpu_type]

            if ('Memory_type' not in value.keys()):
                print("*****Error: group %s has not specified Memory type" % key)
                sys.exit()
            mem_type = value['Memory_type']
            value['MEM'] = comp[mem_type]

        return group


def parse_config_file(cfgFile):
    config_data = []
    with open(cfgFile, 'r') as config_file:

        for line in config_file:
            if not line.strip():
                continue
            line = line.strip()
            if line.startswith('#'):
                config_data.append(line)
            else:
                tokens = line.split()
                key = tokens[0].strip()
                value = ' '.join(tokens[1:]).strip()
                config_data.append((key, value))
    return config_data


def gpu_config_gen(config_data, config_file_name):
    config_file_path = f"{config_file_name}"
    with open(config_file_path, 'w') as config_file:
        for item in config_data:
            if isinstance(item, str):
                config_file.write(item + '\n')
            else:
                config_file.write(f"{item[0]} {item[1]}\n")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--config", help = "specify configuration file", required = True)
    parser.add_argument("-j", "--json", help = "specify json file", required = True)
    parser.add_argument("-o", "--output", help = "specify config file path", required = True)
    parser.add_argument("-m", "--mode", help = "specify config file path", required = True)
    args = parser.parse_args()
    cfgFile = args.config
    jsonFile = args.json
    outputFile = args.output
    gpuMode = args.mode

    config_data = parse_config_file(cfgFile)
    jp = JsonParser(jsonFile)
    group_base, net_base = jp.parse()
    print(next(iter(group_base)))
    a = group_base[next(iter(group_base))]['GPU']
    n = 0
    for i, item in enumerate(config_data):
        for key in group_base[next(iter(group_base))]['GPU']:
            if isinstance(item, tuple) and item[0] == key:
                config_data[i] = (key, group_base[next(iter(group_base))]['GPU'][key])
        if(config_data[i][0]== "-gpgpu_ptx_sim_mode"):
            config_data[i] = ("-gpgpu_ptx_sim_mode", gpuMode)

    gpu_config_gen(config_data, outputFile)



if __name__ == "__main__":
    main()
    # jsonFile = "../../config.json"

    # with open(jsonFile,'r', encoding='UTF-8') as f:
    #     load_dict = json.load(f)
    # design_file = load_dict['basePath'] + load_dict['moduleA']['xml_json_file']
    # print(load_dict)
    # # jp = JsonParser(jsonFile)
    # # group_base, net_base = jp.parse()

    # a = load_dict['basePath'] + load_dict['moduleA']['config_design_file']
    # print(a)
    # n = 0
    # for i, item in enumerate(config_data):
    #     for key in group_base['GROUP_A']['GPU']:
    #         if isinstance(item, tuple) and item[0] == key:
    #             config_data[i] = (key, group_base['GROUP_A']['GPU'][key])

    # gpu_config_gen(config_data, "gpgpusim.config")
